<template>
  <div class="login-container" v-loading="loading">
    <div class="loadingShadow" v-show="loadingShadow"></div>
    <el-form ref="loginForm" :model="loginForm" :rules="loginRules" class="login-form" auto-complete="on">
      <div class="title-container">
        <h3 class="title">登录系统</h3>
      </div>
      <el-form-item prop="username">
        <span class="svg-container">
          <svg-icon icon-class="user" />
        </span>
        <el-input ref="username" v-model="loginForm.account" placeholder="请输入用户名" name="username" type="text" tabindex="1" auto-complete="on" />
      </el-form-item>
      <el-form-item prop="password">
        <span class="svg-container">
          <svg-icon icon-class="password" />
        </span>
        <el-input :key="passwordType" ref="password" v-model="loginForm.password" :type="passwordType" placeholder="请输入密码" name="password" tabindex="2" auto-complete="on" @keyup.enter.native="handleLogin" />
        <span class="show-pwd" @click="showPwd">
          <svg-icon :icon-class="passwordType === 'password' ? 'eye' : 'eye-open'" />
        </span>
      </el-form-item>
      <el-button :loading="loading" type="primary" style="width:100%;margin-bottom:30px;" @click.native.prevent="handleLogin">登 陆</el-button>
    </el-form>
  </div>
</template>

<script>
import {
  getencryptionCookie,
  passwordCookie,
  accountCookie,
  getpasCookie,
} from "@/utils/cookie";
import crypto from "crypto-js";
import StyleCustomConfigurationApi from "@/api/basic-info-manage/style-custom-configuration/index";
import variables from "@/styles/variables.scss";
import store from "@/store";
export default {
  name: "LoginPage",
  data() {
    const validateUsername = (rule, value, callback) => {
      if (!value) {
        callback(new Error("请输入用户名"));
      } else {
        callback();
      }
    };
    const validatePassword = (rule, value, callback) => {
      if (value.length < 6) {
        callback(new Error("密码不得小于6位数"));
      } else {
        callback();
      }
    };
    return {
      loginForm: {
        account: "",
        password: "",
      },
      loginRules: {
        account: [
          { required: true, trigger: "blur", validator: validateUsername },
        ],
        password: [
          { required: true, trigger: "blur", validator: validatePassword },
        ],
      },
      loadingShadow: false,
      loading: false,
      passwordType: "password",
      redirect: undefined,
    };
  },
  //entrance_flag 这个字段判断系统来源
  //entrance_flag：IADPLO 农业平台统一登录
  //entrance_flag：IADP 演示环境统一登录
  watch: {
    $route: {
      handler: function (route) {
        this.getUrlParams(route);
      },
      immediate: true,
    },
  },
  // http://192.168.31.86:8080/#/login?account=U2FsdGVkX19zORCLHejdwmY6sQfXrZrTyxNsMkvwD%2Fp8jAMqCR0xLMc3af3apMLu&password=U2FsdGVkX1%2B7nmuH2Zav4iLPvLt7Ov6Stxt1rf2giq8%3D&organizationNo=Test2&entrance_flag=IADP&farmingTypeNo=sc&farming=FISH
  methods: {
    isAutoLogin(entrance_flag) {
      if (entrance_flag == "IADPLO") {
        this.loadingShadow = true;
        this.timer = setTimeout(() => {
          this.loadingShadow = false;
        }, 5000);
      } else {
        this.loadingShadow = false;
      }
    },
    getUrlParams(route) {
      this.redirect = route.query && route.query.redirect;
      let {
        token,
        account,
        password,
        entrance_flag,
        farming,
        virtualSystemNo,
      } = route.query;
      //拒绝铭文账号密码
      //能通过url带出的账号密码必须加密
      if (account && password) {
        //如果以加密账号密码不合并的形势传过来的需要解密登录
        let loginForm = {
          account: this.decodeToken(
            account.trim(),
            "thisisafakeaccount123456789"
          ),
          password: this.decodeToken(
            password.trim(),
            "thisisafakepassword123456789"
          ),
        };
        this.userLogin(loginForm);
      } else if (token) {
        //如果以token的形势传过来的就直接通过getpasCookie解密获取账号密码登录
        //这里的token并非请求的token而是加密后的账号密码
        let urlInfo = decodeURIComponent(
          window.location.href.split("?")[1].split("=")[1]
        ).replace(/ /g, "+");
        let obj = getpasCookie(urlInfo);
        account = obj.account;
        password = obj.password;
        let loginForm = { account, password };
        this.userLogin(loginForm);
      } else {
        this.loading = false;
      }
      //系统来源标识存session
      entrance_flag &&
        sessionStorage.setItem("entrance_flag", entrance_flag || "");
      virtualSystemNo &&
        sessionStorage.setItem("virtualSystemNo", virtualSystemNo || "");
      farming && sessionStorage.setItem("farming", farming || "");
      this.isAutoLogin(entrance_flag);
    },
    showPwd() {
      if (this.passwordType === "password") {
        this.passwordType = "";
      } else {
        this.passwordType = "password";
      }
      this.$nextTick(() => {
        this.$refs.password.focus();
      });
    },
    //解密
    decodeToken(info, key) {
      return crypto.AES.decrypt(info, key).toString(crypto.enc.Utf8);
    },
    handleLogin() {
      this.$refs.loginForm.validate((valid) => {
        if (valid) {
          this.userLogin(this.loginForm);
        } else {
          console.log("error submit!!");
          return false;
        }
      });
    },
    userLogin(loginForm) {
      this.loading = true;
      this.$store
        .dispatch("user/login", loginForm)
        .then(() => {
          let { account, password } = loginForm;
          let routerParams = {
            account: accountCookie(account),
            username: account,
            password: passwordCookie(password),
            accountPassword: getencryptionCookie(account, password),
          };
          for (let key in routerParams) {
            routerParams[key] && sessionStorage.setItem(key, routerParams[key]);
          }
          sessionStorage.setItem("userInfo", JSON.stringify(routerParams));
          this.$router.push({ path: "/chooseSystem" });
          this.loading = false;
        })
        .catch((err) => {
          this.$message.warning(err || "用户名或密码错误！");
          this.loading = false;
        });
    },
  },
};
</script>

<style lang="scss">
$bg: #283443;
$light_gray: #fff;
$cursor: #fff;

@supports (-webkit-mask: none) and (not (cater-color: $cursor)) {
  .login-container .el-input input {
    color: $cursor;
  }
}

/* reset element-ui css */
.login-container {
  .el-input {
    display: inline-block;
    height: 47px;
    width: 85%;

    input {
      background: transparent;
      border: 0px;
      appearance: none;
      border-radius: 0px;
      padding: 12px 5px 12px 15px;
      color: $light_gray;
      height: 47px;
      caret-color: $cursor;

      &:-webkit-autofill {
        box-shadow: 0 0 0px 1000px $bg inset !important;
        -webkit-text-fill-color: $cursor !important;
      }
    }
  }

  .el-form-item {
    border: 1px solid rgba(255, 255, 255, 0.1);
    background: rgba(0, 0, 0, 0.1);
    border-radius: 5px;
    color: #454545;
  }
}
</style>

<style lang="scss" scoped>
$bg: #2d3a4b;
$dark_gray: #889aa4;
$light_gray: #eee;

.login-container {
  min-height: 100%;
  width: 100%;
  background-color: $bg;
  overflow: hidden;

  .login-form {
    position: relative;
    width: 520px;
    max-width: 100%;
    padding: 160px 35px 0;
    margin: 0 auto;
    overflow: hidden;
  }

  .tips {
    font-size: 14px;
    color: #fff;
    margin-bottom: 10px;

    span {
      &:first-of-type {
        margin-right: 16px;
      }
    }
  }

  .svg-container {
    padding: 6px 5px 6px 15px;
    color: $dark_gray;
    vertical-align: middle;
    width: 30px;
    display: inline-block;
    .svg-icon {
      filter: brightness(100);
    }
  }

  .title-container {
    position: relative;

    .title {
      font-size: 26px;
      color: $light_gray;
      margin: 0px auto 40px auto;
      text-align: center;
      font-weight: bold;
    }
  }

  .show-pwd {
    position: absolute;
    right: 10px;
    top: 7px;
    font-size: 16px;
    color: $dark_gray;
    cursor: pointer;
    user-select: none;
    .svg-icon {
      filter: brightness(100);
    }
  }
}

::v-deep .el-loading-mask {
  background-color: #ffffff !important;
}
.loadingShadow {
  position: fixed;
  top: 0;
  left: 0;
  width: 100vw;
  height: 100vh;
  background-color: #ffffff;
  z-index: 1000;
}
</style>
